package com.ads.proplan.activity;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.widget.ArrayAdapter;

import com.ads.proplan.db.JogadorRepository;
import com.ads.proplan.db.UsuarioRepository;
import com.ads.proplan.db.entity.Jogador;
import com.ads.proplan.db.entity.RankngResumo;
import com.ads.proplan.db.entity.Usuario;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class RankingFragment extends ListFragment {

	protected JogadorRepository jogadorRepos;
	protected ArrayList<Jogador> arrayListJogador;
	protected Jogador jogadorEntity;
	
	protected UsuarioRepository usuarioRepos;
	protected ArrayList<Usuario> arrayListUsuario;
	protected Usuario usuarioEntity;
	
	public static final String ARG_OBJECT = "object";
//	private String valueIp = "172.18.9.98";
	private String valueIp = "192.168.0.104";
	List<String> arrayList = new ArrayList<String>();
	Handler handler = new Handler();
	
	@Override
	  public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		conct();
	}
	
	private void montarLista() {
		handler.post(new Runnable() {
			@Override
			public void run() {
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, arrayList);
				setListAdapter(adapter);
			}
		});
	}

	public void conct(){
		Thread thread = new Thread()
		{
		    @Override
		    public void run() {
				try {
					setGsonWeb();
					getGsonWeb();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    }
		};
		thread.start();
	}
	
	void getGsonWeb() throws MalformedURLException, IOException {
		InputStream input = new URL("http://"+valueIp+":8085/Quiz/ranking").openStream();
		Reader reader = new InputStreamReader(input, "UTF-8");
		List<RankngResumo> results = new Gson().fromJson(reader,
				new TypeToken<List<RankngResumo>>() {
				}.getType());
		
		for (RankngResumo rankngResumo : results) {
			arrayList.add("Nome: "+rankngResumo.getNome()+", Pontos: "+rankngResumo.getPontos());
		}
		montarLista();
	}
	
	void setGsonWeb() throws MalformedURLException, IOException {
		getJogador(this.getActivity());
		getUsuario(this.getActivity());
		RankngResumo rankngResumo = new RankngResumo();
		rankngResumo.setNome(usuarioEntity.getNome());
		rankngResumo.setPontos(jogadorEntity.getPontos());
		HttpClient httpclient = new DefaultHttpClient();
		Log.i("GSONSET","antes Url");
        HttpPost httpPost = new HttpPost("http://"+valueIp+":8085/Quiz/ranking?action=VERIFICAR");
        Log.i("GSONSET","depois Url");
        String json = new Gson().toJson(rankngResumo);
        StringEntity se = new StringEntity(json);
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        HttpParams params = new BasicHttpParams();          
        params.setParameter("action", "VERIFICAR");
        httpPost.setParams(params);
        Log.i("GSONSET","antes executar");
        HttpResponse httpResponse = httpclient.execute(httpPost);
        Log.i("GSONSET","depois de executar");

//        InputStream inputStream = httpResponse.getEntity().getContent();
        
	}
	
	protected void getJogador(Context context) {
		if (jogadorRepos == null) {
			jogadorRepos = new JogadorRepository(context);
			arrayListJogador = (ArrayList<Jogador>) jogadorRepos.getAll();
			jogadorEntity = arrayListJogador.get(0);
		}
	}
	
	protected void getUsuario(Context context) {
		if (usuarioRepos == null) {
			usuarioRepos = new UsuarioRepository(context);
			arrayListUsuario = (ArrayList<Usuario>) usuarioRepos.getAll();
			usuarioEntity = arrayListUsuario.get(0);
		}
	}
}
